<template>
  <div class="box">
    <el-container class="highCont">
      <el-header>
        <div class="logo" @click="backHome">
          <img src="@/assets/logo.png" :alt="$t('picisgone')" />
          <span class="title">{{$t('backmansys')}}</span>
        </div>
        <div class="percen">
          <el-dropdown class="messageMenu" @command="getMessageItem">
            <span class="permsg">
              <span class="msg">{{$t('message')}}</span>
              <el-badge :value="messageNum" :max="99" class="reddot" :hidden="dotShow">
                <img src="@/assets/bell.png" :alt="$t('picisgone')" ref="logoutMao">
              </el-badge>
            </span>
            <el-dropdown-menu slot="dropdown">
              <el-dropdown-item command="/feedback" v-if="role === 'fake'" class="feedMessage">
                {{$t('userfeedback')}}
                <sup class="unread" v-if="totalUnreadCount !== 0">
                  <template v-if="totalUnreadCount > 99">99+</template>
                  <template v-else>{{totalUnreadCount}}</template>
                </sup>
              </el-dropdown-item>
            </el-dropdown-menu>
          </el-dropdown>
          <!-- <el-dropdown class="language" @command="handlelang">
            <span class="el-dropdown-link">
                {{$t('swithelan')}}<i class="el-icon-arrow-down el-icon--right"></i>
            </span>
            <el-dropdown-menu slot="dropdown">
                <el-dropdown-item command="zh-CN">中文</el-dropdown-item>
                <el-dropdown-item command="en">English</el-dropdown-item>
            </el-dropdown-menu>
          </el-dropdown> -->
          <el-button class="perbtn" @click="userLogout">{{$t('logout')}}</el-button>
        </div>
      </el-header>
      <el-container class="lessCont">
        <el-aside width="200px">
          <div class="perasd">
            <img class="headprot" src="@/assets/keyl.jpg">
            <div>{{keyName}}</div>
          </div>
          <el-menu :default-active="activePath" unique-opened :collapse-transition="true" ref="activemenu" router>
              <el-submenu :index="'/' + i" v-for="(item, i) in asideList" :key="item.id">
                  <template slot="title">
                    <img src="@/assets/shangpin.png">
                    <span class="mgmt">{{item.text}}</span>
                  </template>
                  <el-menu-item :id="'menu' + subitem.id" :index="subitem.url" v-for="(subitem) in item.children" :key="subitem.id" @click="saveNavState(subitem.id, subitem.url)">
                    <i></i>
                    <span>{{subitem.text}}</span>
                  </el-menu-item>
              </el-submenu>
          </el-menu>
        </el-aside>
        <el-main>
          <router-view :key="key"></router-view>
        </el-main>
      </el-container>
    </el-container>
  </div>
</template>

<script>
import Cookies from 'js-cookie'
// import { Notification } from 'element-ui'
// import { mapState, mapGetters } from 'vuex'
import { getMenu } from '@/libs/reqlist.js'
// import shangp from '@/assets/shangpin.png'
// import huod from '@/assets/huodong.png'
// import sheq from '@/assets/shequ.png'
// import dind from '@/assets/dindan.png'
// import yongh from '@/assets/yonghu.png'
// import kef from '@/assets/kefu.png'
// import yuanj from '@/assets/yuanjian.png'
// import shejk from '@/assets/shejiku.png'
// import kuc from '@/assets/kucun.png'
// import hout from '@/assets/houtai.png'
export default {
  computed: {
    key () {
      return this.$route.name !== undefined? this.$route.name + +new Date(): this.$route + +new Date()
    },
    // ...mapGetters(['totalUnreadCount']),
    // ...mapState({
    //   currentUserProfile: state => state.user.currentUserProfile,
    //   currentConversation: state => state.conversation.currentConversation,
    //   isLogin: state => state.user.isLogin,
    //   isSDKReady: state => state.user.isSDKReady,
    //   isBusy: state => state.video.isBusy,
    //   userID: state => state.user.userID
    // }),
    messageNum () {
      return this.totalUnreadCount
    }
  },
  mounted () {
    // this.initListener()
    if (window.sessionStorage.getItem('activePath')) this.activePath = window.sessionStorage.getItem('activePath')
    let aturl = window.location.href.split('/')
    if (this.activePath) {
      if (aturl[aturl.length - 1] === 'home') {
        this.$router.push(this.activePath)
      }
    }
    this.keyName = window.localStorage.getItem('jounery')
    this.init()
    this.role = Cookies.get('feed')
    // if (Cookies.get('feed') === 'fake') {
    //   this.userForm.userID = window.localStorage.getItem('jounery')
    //   this.serviceLogin()
    // }
    // window.setInterval(() => {
    //   setTimeout(this.getMessage, 0)
    // }, 30000)
    this.$on("hook:beforeDestroy", () => {
      Cookies.remove('isRef')
    })
  },
  watch: {
    // 监听导航栏输入url事件
    $route (to) {
      if (to.path == '/404') {
        let parOne = document.querySelector('.el-menu')
        let endOne = document.querySelector('.is-opened')
        if (parOne !== null) {
          if (endOne !== null) {
            for (let i = 0; i < parOne.childNodes.length; i++) {
              let item = parOne.childNodes[i]
              // endOne.outerText.replace(/\n/g, '|').split('|')[0] ----- 使用'|'符号替换字符串中的回车符
              if (item.outerText === endOne.outerText) {
                this.penIndex = '/' + i
              }
            }
          }
        }
        this.$refs.activemenu.close(this.penIndex)
      }
      if (to.path.indexOf('/sec') === -1) {
        this.activePath = to.path
        window.sessionStorage.setItem('activePath', to.path)
      }
    },
    isLogin(next) {
      if (next) {
        // MTA.clickStat('link_two', { show: 'true' })
      }
    }
  },
  data() {
    return {
      dotShow: true,
      // 用户名
      keyName: '',
      // 默认展开菜单
      activePath: '',
      // 当前选中菜单index
      penIndex: '',
      // 侧边栏菜单数据
      asideList: [],
      userForm: {
        userID: ''
      },
      role: ''
    };
  },
  methods: {
    init () {
      if (window.sessionStorage.getItem('userMenuRef') == undefined) window.sessionStorage.setItem('userMenuRef', 'mp')
      switch (window.sessionStorage.getItem('userMenuRef')) {
        case 'mp':
          getMenu(Cookies.get('sysUserID')).then(async (res) => {
            if (res.data.code == 0) {
              this.asideList = res.data.data
              sessionStorage.setItem('userMenuList', JSON.stringify(this.asideList))
              window.sessionStorage.setItem('userMenuRef', 'ms')
              let secMenu = []
              await this.asideList.forEach(item => {
                if (item.children) item.children.forEach(real => {
                  secMenu.push(real)
                })
              })
              sessionStorage.setItem('roleMenu', JSON.stringify(secMenu))
            }
          })
          break;
        case 'ms':
          this.asideList = JSON.parse(sessionStorage.getItem('userMenuList'))
          break;
      }
    },
    // 保存选中菜单状态
    saveNavState (id, path) {
      let parOne = document.querySelector('.el-menu')
      let endOne = document.querySelector('.is-opened')
      if (parOne !== null) {
        for (let i = 0; i < parOne.childNodes.length; i++) {
          let item = parOne.childNodes[i]
          // endOne.outerText.replace(/\n/g, '|').split('|')[0] ----- 使用'|'符号替换字符串中的回车符
          if (item.outerText === endOne.outerText) {
            this.penIndex = '/' + i
          }
        }
      }
      window.sessionStorage.setItem('activePath', path)
    },
    // 返回首页
    backHome () {
      let parOne = document.querySelector('.el-menu')
      let endOne = document.querySelector('.is-opened')
      if (parOne !== null) {
        if (endOne !== null) {
          for (let i = 0; i < parOne.childNodes.length; i++) {
            let item = parOne.childNodes[i]
            // endOne.outerText.replace(/\n/g, '|').split('|')[0] ----- 使用'|'符号替换字符串中的回车符
            if (item.outerText === endOne.outerText) {
              this.penIndex = '/' + i
            }
          }
        }
      }
      this.$refs.activemenu.close(this.penIndex)
      this.activePath = '/home'
      this.$router.push('/home')
      window.sessionStorage.removeItem('activePath')
    },
    // 切换语言
    handlelang (command) {
      Cookies.set('isRef', true)
      Cookies.set('language', command)
      this.$router.go(0)
    },
    // 退出
    userLogout () {
      this.$router.push('/login')
      this.$message({
        type: 'success',
        message: this.$t('logoutsuc')
      })
      if (Cookies.get('feed') === 'fake') this.$store.dispatch('logout')
      Cookies.remove('cle')
      Cookies.remove('feed')
      sessionStorage.removeItem('roleMenu')
      window.sessionStorage.removeItem('userMenuRef')
      sessionStorage.removeItem('userMenuList')
      window.sessionStorage.removeItem('activePath')
    },
    // 前往详细的消息页
    getMessageItem (command) {
      this.$router.push(command)
    },
    // 客服登录
    // serviceLogin () {
    //   this.tim
    //     .login({
    //       userID: this.userForm.userID,
    //       userSig: window.genTestUserSig(this.userForm.userID).userSig
    //     })
    //     .then(() => {
    //       this.loading = false
    //     })
    //     .catch(error => {
    //       this.loading = false
    //       this.$message.error(this.$t('loginfail') + error.message)
    //     })
    // },
    // initListener() {
    //     // 登录成功后会触发 SDK_READY 事件，该事件触发后，可正常使用 SDK 接口
    //     this.tim.on(this.TIM.EVENT.SDK_READY, this.onReadyStateUpdate, this)
    //     // SDK NOT READT
    //     this.tim.on(this.TIM.EVENT.SDK_NOT_READY, this.onReadyStateUpdate, this)
    //     // 被踢出
    //     this.tim.on(this.TIM.EVENT.KICKED_OUT, this.onKickOut)
    //     // SDK内部出错
    //     this.tim.on(this.TIM.EVENT.ERROR, this.onError)
    //     // 收到新消息
    //     this.tim.on(this.TIM.EVENT.MESSAGE_RECEIVED, this.onReceiveMessage)
    //     // 会话列表更新
    //     this.tim.on(this.TIM.EVENT.CONVERSATION_LIST_UPDATED, this.onUpdateConversationList)
    //     // 网络监测
    //     this.tim.on(this.TIM.EVENT.NET_STATE_CHANGE, this.onNetStateChange)
    //     // 已读回执
    //     this.tim.on(this.TIM.EVENT.MESSAGE_READ_BY_PEER, this.onMessageReadByPeer)
    //   },
    //   onReceiveMessage({ data: messageList }) {
    //     this.handleAt(messageList)
    //     this.$store.commit('pushCurrentMessageList', messageList)
    //   },
    //   onError({ data }) {
    //     if (data.message !== 'Network Error') {
    //       // this.$store.commit('showMessage', {
    //       //   message: data.message,
    //       //   type: 'error'
    //       // })
    //       this.$message.error({
    //         message: data.message
    //       })
    //     }
    //   },
    //   onMessageReadByPeer() {},
    //   onReadyStateUpdate({ name }) {
    //     const isSDKReady = name === this.TIM.EVENT.SDK_READY ? true : false
    //     this.$store.commit('toggleIsSDKReady', isSDKReady)

    //     if (isSDKReady) {
    //       this.tim
    //         .getMyProfile()
    //         .then(({ data }) => {
    //           this.$store.commit('updateCurrentUserProfile', data)
    //         })
    //         .catch(error => {
    //           // this.$store.commit('showMessage', {
    //           //   type: 'error',
    //           //   message: error.message
    //           // })
    //           this.$message.error({
    //             message: error.message
    //           })
    //         })
    //     }
    //   },
    //   kickedOutReason(type) {
    //     switch (type) {
    //       case this.TIM.TYPES.KICKED_OUT_MULT_ACCOUNT:
    //         return this.$t('duetomultiplelogins')
    //       case this.TIM.TYPES.KICKED_OUT_MULT_DEVICE:
    //         return this.$t('loginduetomultipledevices')
    //       case this.TIM.TYPES.KICKED_OUT_USERSIG_EXPIRED:
    //         return this.$t('duetoexpiredpass')
    //       default:
    //         return ''
    //     }
    //   },
    //   checkoutNetState(state) {
    //     switch (state) {
    //       case this.TIM.TYPES.NET_STATE_CONNECTED:
    //         return { message: this.$t('plugintothenetwork'), type: 'success' }
    //       case this.TIM.TYPES.NET_STATE_CONNECTING:
    //         return { message: this.$t('thecurrentnetworkisunstable'), type: 'warning' }
    //       case this.TIM.TYPES.NET_STATE_DISCONNECTED:
    //         return { message: this.$t('thenetworkiscurrentlyunavailable'), type: 'error' }
    //       default:
    //         return ''
    //     }
    //   },
    //   onNetStateChange(event) {
    //     this.$message(this.checkoutNetState(event.data.state))
    //   },
    //   onKickOut(event) {
    //     this.$message.error({
    //       message: `${this.kickedOutReason(event.data.type)}${this.$t('havebeenkickedoutpleaseloginagain')}。`
    //     })
    //     this.$store.commit('toggleIsLogin', false)
    //     this.$store.commit('reset')
    //   },
    //   onUpdateConversationList(event) {
    //     this.$store.commit('updateConversationList', event.data)
    //   },
    //   /**
    //    * 处理 @ 我的消息
    //    * @param {Message[]} messageList
    //    */
    //   handleAt(messageList) {
    //     // 筛选有 @ 符号的文本消息
    //     const atTextMessageList = messageList.filter(
    //       message =>
    //         message.type === this.TIM.TYPES.MSG_TEXT &&
    //         message.payload.text.includes('@')
    //     )
    //     for (let i = 0; i < atTextMessageList.length; i++) {
    //       const message = atTextMessageList[i]
    //       const matched = message.payload.text.match(/@\w+/g)
    //       if (!matched) {
    //         continue
    //       }
    //       // @ 我的
    //       if (matched.includes(`@${this.currentUserProfile.userID}`)) {
    //         // 当前页面不可见时，调用window.Notification接口，系统级别通知。
    //         if (this.$store.getters.hidden) {
    //           this.notifyMe(message)
    //         }
    //         Notification({
    //           title: `有人在群${message.conversationID.slice(5)}提到了你`,
    //           message: message.payload.text,
    //           duration: 3000
    //         })
    //         this.$bus.$emit('new-messsage-at-me', {
    //           data: { conversationID: message.conversationID }
    //         })
    //       }
    //     }
    //   },
    //   selectConversation(conversationID) {
    //     if (conversationID !== this.currentConversation.conversationID) {
    //       this.$store.dispatch('checkoutConversation',conversationID)
    //     }
    //   },
    //   isJsonStr(str) {
    //     try{
    //       JSON.parse(str)
    //       return true
    //     }catch {
    //       return false
    //     }
    //   },
    //   /**
    //    * 使用 window.Notification 进行全局的系统通知
    //    * @param {Message} message
    //    */
    //   notifyMe(message) {
    //     // 需检测浏览器支持和用户授权
    //     if (!('Notification' in window)) {
    //       return
    //     } else if (window.Notification.permission === 'granted') {
    //       this.handleNotify(message)
    //     } else if (window.Notification.permission !== 'denied') {
    //       window.Notification.requestPermission().then(permission => {
    //         // 如果用户同意，就可以向他们发送通知
    //         if (permission === 'granted') {
    //           this.handleNotify(message)
    //         }
    //       })
    //     }
    //   },
    //   handleNotify(message) {
    //     const notification = new window.Notification('有人提到了你', {
    //       icon: 'https://webim-1252463788.file.myqcloud.com/demo/img/logo.dc3be0d4.png',
    //       body: message.payload.text
    //     })
    //     notification.onclick = () => {
    //       window.focus()
    //       this.$store.dispatch('checkoutConversation', message.conversationID)
    //       notification.close()
    //     }
    //   }
  }
};
</script>

<style lang="less" scoped>
@import "./pageBox.less";
</style>
